const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session=require('koa-generic-session');
const Redis=require('koa-redis');
const pv=require('./middleware/koa-pv');
const m1=require('./middleware/m1');
const m2=require('./middleware/m2');
const index = require('./routes/index')
const users = require('./routes/users')
const mongoose=require('mongoose');
const dbConfig=require("./dbs/config.js");

// error handler
onerror(app)
//app.keys = ['some secret hurr'];//用来加密cookie
app.keys=['keysssss'];
app.use(session({ //这里加一个配置，store:new Redis(),不写的话默认把session放进内存了。
   key:'test',//加key 加prefix参数，是为了修改cookie里的签名的字段名。
   prefix:'test_pr',
   store:new Redis()  //参数不写为本机默认端口
}));
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(logger())
app.use(pv())
app.use(m1())
app.use(m2())

app.use(json())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
//连接数据库
mongoose.connect(dbConfig.dbs,{
   useNewUrlParser:true
})
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
